package com.huluobo.lc.ppjoke_jetpack.utils;


import android.content.ComponentName;

import androidx.fragment.app.FragmentActivity;
import androidx.navigation.ActivityNavigator;
import androidx.navigation.NavController;
import androidx.navigation.NavGraph;
import androidx.navigation.NavGraphNavigator;
import androidx.navigation.NavigatorProvider;
import androidx.navigation.fragment.FragmentNavigator;

import com.huluobo.lc.libcommon.AppGlobals;
import com.huluobo.lc.ppjoke_jetpack.model.Destination;

import java.util.HashMap;

/**
 * @author Lc
 * @description: 功能:节点跳转,通过fragment和activity的注解,获取到具体的activity和fragment,以节点的方式进行跳转和切换
 * @date :2020/7/7 11:43
 */
public class NavGraphBuilder {
    public static void build(NavController controller, FragmentActivity activity, int containerId) {
        NavigatorProvider navigatorProvider = controller.getNavigatorProvider();//HashMap对象,
        // 这里存放了所有activity和fragment的所有页面节点

//        FragmentNavigator fragmentNavigator =
//                navigatorProvider.getNavigator(FragmentNavigator.class);
        FixFragmentNavigator fragmentNavigator = new FixFragmentNavigator(activity,
                activity.getSupportFragmentManager(), containerId);
        navigatorProvider.addNavigator(fragmentNavigator);
        ActivityNavigator activityNavigator =
                navigatorProvider.getNavigator(ActivityNavigator.class);

        NavGraph navGraph = new NavGraph(new NavGraphNavigator(navigatorProvider));//节点控制器
        HashMap<String, Destination> destConfig = AppConfig.getsDestConfig();//拿到所有的被注解标注的信息
        for (Destination value : destConfig.values()) {
            if (value.isIsFragment()) {
                FragmentNavigator.Destination destination = fragmentNavigator.createDestination();
                destination.setClassName(value.getClzName());//具体的某一个fragment
                destination.setId(value.getId());//fragment的id
                destination.addDeepLink(value.getPageUrl());//标注跳转的隐式意图

                navGraph.addDestination(destination);
            } else {
                ActivityNavigator.Destination destination =
                        activityNavigator.createDestination();//创建页面节点
                destination.setId(value.getId());
                destination.addDeepLink(value.getPageUrl());
                destination.setComponentName(new ComponentName(AppGlobals.getApplication().getPackageName(), value.getClzName()));

                navGraph.addDestination(destination);
            }

            if (value.isAsStarter()) {//通过节点信息中的AsStarter,来控制显示的首页
                //如果这个页面是进入的首页
                navGraph.setStartDestination(value.getId());//首页fragment
            }
        }

        controller.setGraph(navGraph);//把导航器赋值给控制器
    }
}
